import { message } from '@renderer/utils'
import dayjs from 'dayjs'
import { defineStore } from 'pinia'

const todoStore = defineStore('todoStore', {
  state: (): TodoState => ({
    todoList: [],
    todo: undefined,
    todoNavList: [],
    rightMenuTodo: undefined,
    trashList: []
  }),
  actions: {
    async pullData() {
      this.todoList = []
      this.todoList = await window.api.getTodoDataList()
      return this.todoList
    },
    async getTodoNavList() {
      this.todoNavList = []
      this.todoNavList = await window.api.getTodoNavList()
      return this.todoNavList
    },
    async getTrashList() {
      this.trashList = []
      this.trashList = await window.api.getTrashData()
    },
    restoreTrashData(id: string) {
      this.trashList = this.trashList.filter((item) => item.id !== id)
      window.api.restoreTrashData(id)
      message({
        type: 'sucess',
        content: '任务已恢复'
      })
      this.todo = undefined
      this.getTrashList()
      this.pullData()
    },
    getTodoGroupCount(groupName: string) {
      if (groupName === '今天') {
        return this.todoList.filter((item) => {
          return (
            item.group === '收集箱' &&
            (dayjs(item.deadlineDate).isSame(dayjs(), 'day') ||
              dayjs(item.doneDate).isSame(dayjs(), 'day'))
          )
        }).length
      }
      if (groupName === '最近7天') {
        return this.todoList.filter(
          (item) => dayjs(item.deadlineDate).isSame(Date.now(), 'week') && item.group === '收集箱'
        ).length
      }
      if (groupName === '收集箱') {
        return this.todoList.filter((item) => item.group === '收集箱').length
      }
      if (groupName === '已完成') {
        return this.todoList.filter((item) => item.isDone && item.group === '收集箱').length
      }
      if (groupName === '垃圾桶') {
        return this.trashList.length
      }
      if (groupName) {
        return this.todoList.filter((item) => item.group === groupName).length
      }
      return 0
    },
    handleTodoExpand(taskGroup: TodoGroup) {
      taskGroup.expand = !taskGroup.expand
      const groupExpandMap = JSON.parse(localStorage.getItem('groupExpandMap') || '{}')
      groupExpandMap[taskGroup.path] = {
        ...groupExpandMap[taskGroup.path],
        [taskGroup.groupName]: taskGroup.expand
      }
      localStorage.setItem('groupExpandMap', JSON.stringify(groupExpandMap))
    },
    getGroupExpand(path: string, key: string) {
      const groupExpandMap = localStorage.getItem('groupExpandMap') || '{}'
      const groupExpandMapObject = JSON.parse(groupExpandMap)
      let expand = false
      if (groupExpandMapObject[path]) {
        expand = groupExpandMapObject[path][key] || true
      }
      return expand
    },
    handleAddTodo(e: KeyboardEvent, groupName: string) {
      if (e.isComposing) {
        return
      }
      const input = e.target as HTMLInputElement
      if (!input.value.trim()) {
        return
      }
      const now = new Date()
      const date = now
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false // 使用 24 小时制
        })
        .replace(/\//g, '-') // 将 / 替换为 -
      const deadlineDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false // 使用 24 小时
        })
        .replace(/\//g, '-') // 将 / 替换为 -
      const todoObject: TodoItem = {
        id: Date.now().toString(),
        title: input.value,
        group: groupName,
        isDone: false,
        createDate: date,
        updateDate: date,
        doneDate: '',
        deadlineDate,
        isDelete: false,
        isImportant: false,
        content: '',
        description: ''
      }
      window.api.addTodoData(todoObject)
      this.todoList.push(todoObject)
      input.value = ''
    },
    handleDeleteTodo(id: string) {
      this.todoList = this.todoList.filter((item) => item.id !== id)
      window.api.deleteTodoData(id)
      message({
        type: 'sucess',
        content: '任务已删除'
      })
      this.getTrashList()
    },
    handleDeleteTrashTodo(id: string) {
      this.trashList = this.trashList.filter((item) => item.id !== id)
      window.api.deleteTrashData(id)
      message({
        type: 'sucess',
        content: '任务已删除'
      })
      this.todo = undefined
      this.getTrashList()
    },
    showRightMenu(e: MouseEvent, todo: TodoItem) {
      e.preventDefault()
      e.stopPropagation()
      this.rightMenuTodo = todo
    }
  }
})

export default todoStore
